import { useEffect, useMemo, useState } from 'react';
import { useMediaPredicate } from 'react-media-hook';
import { MediaQuery } from '../constant/Media';

const LIMIT_UNDER_1200 = 5;
const LIMIT_OVER_1200 = 10;

export const usePagination = () => {
  const [page, setPage] = useState<number>(1);
  const [count, setCount] = useState<number>();
  const isBiggerThanMd = useMediaPredicate(MediaQuery.Md);
  const [limit, setLimit] = useState<number>(isBiggerThanMd ? LIMIT_OVER_1200 : LIMIT_UNDER_1200);
  const offset = useMemo(() => (page - 1) * limit, [page]);
  const pageCount = useMemo(() => Math.ceil((count ?? 0) / limit), [count]);

  useEffect(() => {
    setPage(1);
    setCount(0);
  }, [limit]);

  useEffect(() => {
    setLimit(isBiggerThanMd ? LIMIT_OVER_1200 : LIMIT_UNDER_1200);
  }, [isBiggerThanMd]);

  return {
    limit,
    offset,
    setLimit,
    setCount,
    paginationProps: { page, setPage, pageCount },
  };
};
